#include "stdio.h"
#include "stdlib.h"
#include "math.h"

// macro definitions
#define PI 3.1415926
#define EPSILON 1e-5 // precision control, try something bigger or smaller

double getSinX(double);

int main()
{
    printf("%f\n", sin(PI / 2));
    printf("%f\n", getSinX(PI / 2));

    printf("%f\n", sin(PI / 3));
    printf("%f\n", getSinX(PI / 3));

    return 0;
}

/* calculate sin(x) with Taylor expansion:
   sin(x) = x - x^3/3! + 3^5/5! - 3^7/7! + ...
*/
double getSinX(double x)
{
    double result = x;

    int sign = 1;
    double x_power = x;
    long long int fact = 1;
    int n = 1;
    double item;

    do
    {
        sign *= -1; // alternatively, sign = -sign

        x_power *= x * x;
        
        fact *= (n + 1) * (n + 2); 

        item = sign * x_power / fact;

        // printf("%f\n", item);

        result += item;

        n += 2;

    } while (fabs(item) > EPSILON); // what if "item > EPSILON"?

    return result;
}

